package com.hfad.todolistapp;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;

import com.hfad.todolistapp.db.DataBaseManager;
import com.hfad.todolistapp.service.StatusService;
import com.hfad.todolistapp.model.TodoItem;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.gson.Gson;

import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupMenu;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

public class ItemListActivity extends AppCompatActivity implements ToDoStatusChangeCallback {
    private boolean mTwoPane;
    private List<TodoItem> mToDoList = new ArrayList<>();
    private SimpleItemRecyclerViewAdapter mAdapter;
    private RelativeLayout mButtonSortAsc;
    private RelativeLayout mButtonSortDesc;
    private DataBaseManager dbManager;
    private boolean mIsAsc = false;
    private Fragment mDetailFragment = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_item_list);
        dbManager = DataBaseManager.getInstance(this);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setTitle(getTitle());

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // show dialog
                final View dialogContentView = LayoutInflater.from(ItemListActivity.this)
                        .inflate(R.layout.dialog_add_todo, null);
                AlertDialog dialogAddition = new AlertDialog.Builder(ItemListActivity.this)
                        .setTitle("Add ToDo Item")
                        .setView(dialogContentView)
                        .setPositiveButton("Submit", null) // for don't close dialog when button clicked
                        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(getApplicationContext(), "add a new todo canceled", Toast.LENGTH_SHORT).show();
                            }
                        })
                        .create();
                dialogAddition.show();
                dialogAddition.getButton(AlertDialog.BUTTON_POSITIVE)
                        .setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                EditText editTitle = (EditText) dialogContentView.findViewById(R.id.edit_title);
                                EditText editDescription = (EditText) dialogContentView.findViewById(R.id.edit_description);
                                String todoTitle = editTitle.getText().toString();
                                String todoDescription = editDescription.getText().toString();

                                boolean isError = false;
                                if ("".equals(todoTitle.trim())) {
                                    editTitle.setError("Title should not set empty string!");
                                    isError = true;
                                }
                                if ("".equals(todoDescription.trim())) {
                                    editDescription.setError("Description should not set empty string!");
                                    isError = true;
                                }
                                if (isError) {
                                    return;
                                }

                                TodoItem item = new TodoItem();
                                item.setTitle(todoTitle);
                                item.setDescription(todoDescription);
                                item.setHandler("Owner");
                                item.setCreatedTime(System.currentTimeMillis());
                                item.setStatus(TodoItem.ItemStatus.TODO);
                                dbManager.addTodoItem(item);
                                Toast.makeText(getApplicationContext(), "Add a new todo: " + editTitle.getText().toString(), Toast.LENGTH_SHORT).show();

                                editTitle.setText("");
                                editDescription.setText("");
                                dialogAddition.dismiss();

                                mToDoList = dbManager.getTodoItemListOrderByCreatedTime(mIsAsc);
                                mAdapter.notifyDataSetChanged();
                            }
                        });
            }
        });

        if (findViewById(R.id.item_detail_container) != null) {
            // The detail container view will be present only in the
            // large-screen layouts (res/values-w900dp).
            // If this view is present, then the
            // activity should be in two-pane mode.
            mTwoPane = true;
        }

        View recyclerView = findViewById(R.id.item_list);
        assert recyclerView != null;
        setupRecyclerView((RecyclerView) recyclerView);

        mButtonSortAsc = findViewById(R.id.btn_sort_asc);
        mButtonSortAsc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mIsAsc = true;
                mToDoList = dbManager.getTodoItemListOrderByCreatedTime(mIsAsc);
                mAdapter.notifyDataSetChanged();
            }
        });

        mButtonSortDesc = findViewById(R.id.btn_sort_desc);
        mButtonSortDesc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mIsAsc = false;
                mToDoList = dbManager.getTodoItemListOrderByCreatedTime(mIsAsc);
                mAdapter.notifyDataSetChanged();
            }
        });
    }

    private void setupRecyclerView(@NonNull RecyclerView recyclerView) {
        mAdapter = new SimpleItemRecyclerViewAdapter(this, mTwoPane);
        recyclerView.setAdapter(mAdapter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mToDoList = dbManager.getTodoItemListOrderByCreatedTime(false);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onItemStatusChange(int id, TodoItem.ItemStatus status) {
        TodoItem item = dbManager.getTodoItemById(id);
        item.setStatus(status);
        dbManager.updateTodoItem(item);
        mToDoList = dbManager.getTodoItemListOrderByCreatedTime(false);
        mAdapter.notifyDataSetChanged();
    }

    public class SimpleItemRecyclerViewAdapter
            extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {
        private final ItemListActivity mParentActivity;
        private final boolean mTwoPane;

        SimpleItemRecyclerViewAdapter(ItemListActivity parent,
                                      boolean twoPane) {
            mParentActivity = parent;
            mTwoPane = twoPane;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_list_content, parent, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(final ViewHolder holder, int position) {
            TodoItem item = mToDoList.get(position);
            holder.mIdView.setText(String.valueOf(position + 1));
            holder.mTitleView.setText(item.getTitle());
            Calendar cal = Calendar.getInstance(Locale.ENGLISH);
            cal.setTimeInMillis(item.getCreatedTime());
            String date = DateFormat.format("yyyy-MM-dd hh:mm:ss", cal).toString();
            holder.mTimeView.setText(date);

            // update status background
            Drawable statusBackgroundRes = StatusService.getStatusDrawable(
                    holder.itemView.getContext(), item.getStatus()
            );
            holder.mStatusView.setBackground(statusBackgroundRes);

            holder.itemView.setTag(mToDoList.get(position));
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    TodoItem item = (TodoItem) view.getTag();
                    if (mTwoPane) {
                        Bundle arguments = new Bundle();
                        arguments.putString(ItemDetailFragment.ARG_ITEM, new Gson().toJson(item));
                        arguments.putInt(ItemDetailFragment.ARG_INDEX, item.getId());
                        mDetailFragment = new ItemDetailFragment();
                        mDetailFragment.setArguments(arguments);
                        mParentActivity.getSupportFragmentManager().beginTransaction()
                                .replace(R.id.item_detail_container, mDetailFragment)
                                .commit();
                    } else {
                        ItemListActivity activity = (ItemListActivity)view.getContext();
                        Intent intent = new Intent(activity, ItemDetailActivity.class);
                        intent.putExtra(ItemDetailFragment.ARG_ITEM, new Gson().toJson(item));
                        intent.putExtra(ItemDetailFragment.ARG_INDEX, item.getId());
                        activity.startActivity(intent);
                    }
                }
            });
            holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    PopupMenu menu = new PopupMenu(ItemListActivity.this, v);
                    menu.getMenuInflater().inflate(R.menu.menu_item_context_menu, menu.getMenu());
                    menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                        @Override
                        public boolean onMenuItemClick(MenuItem item) {
                            if (item.getItemId() == R.id.action_delete) {
                                TodoItem todoItem = (TodoItem) v.getTag();
                                if (mTwoPane && todoItem.getId() == mToDoList.get(position).getId() && mDetailFragment != null) {
                                    mParentActivity.getSupportFragmentManager().beginTransaction().remove(mDetailFragment).commit();
                                }

                                dbManager.deleteTodoItem(todoItem.getId());
                                mToDoList = dbManager.getTodoItemListOrderByCreatedTime(mIsAsc);
                                mAdapter.notifyDataSetChanged();
                                Toast.makeText(ItemListActivity.this, "Delete Success", Toast.LENGTH_SHORT).show();
                            }
                            return true;
                        }
                    });
                    menu.show();

                    return true;
                }
            });
        }

        @Override
        public int getItemCount() {
            return mToDoList.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            final TextView mIdView;
            final TextView mTitleView;
            final TextView mTimeView;
            final View mStatusView;

            ViewHolder(View view) {
                super(view);
                mIdView = (TextView) view.findViewById(R.id.id_text);
                mTitleView = (TextView) view.findViewById(R.id.text_title);
                mTimeView = view.findViewById(R.id.text_created_time);
                mStatusView = (View) view.findViewById(R.id.view_status);
            }
        }
    }
}